package com.tree.thrive.business.global.filter;

import com.tree.thrive.business.global.net.NetworkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Objects;

/**
 * top-tree
 *
 * @Auther: cheng.tang
 * @Date: 2022/12/5 3:07 PM
 * @Description:
 */
@Slf4j
@Component
public class AccessLogFilter implements Filter {


    private static String collectAllHeaders(HttpServletRequest request) {
        StringBuilder content = new StringBuilder();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            content.append(" [ ")
                    .append(name).append(" : ").append(value)
                    .append(" ] ");
        }
        return content.toString();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String uri = httpServletRequest.getRequestURI();
        String remoteIp = NetworkUtil.getRemoteIp(httpServletRequest);
        String headersContent = collectAllHeaders(httpServletRequest);
        String cookieContent = collectAllCoolies(httpServletRequest);
        log.info(" {} {} {} {} ", uri, remoteIp, headersContent, cookieContent);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private String collectAllCoolies(HttpServletRequest httpServletRequest) {
        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies != null) {
            StringBuilder content = new StringBuilder();
            Arrays.stream(cookies).filter(Objects::nonNull).forEach(cookie -> {
                content.append(" [ ")
                        .append(cookie.getName()).append(" : ").append(cookie.getValue())
                        .append(" ] ");
            });
            return content.toString();
        }
        return "";
    }


}
